package com.xxl.job.admin.core.alarm;

import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.core.model.XxlJobLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class JobAlarmer implements ApplicationContextAware, InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(JobAlarmer.class);

    private ApplicationContext applicationContext;
    private List<JobAlarm> jobAlarmList;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    /**
     * 在所有属性设置完成后执行初始化操作
     * 本方法主要用于初始化JobAlarm bean，通过获取应用上下文中所有JobAlarm类型的bean来进行初始化
     * 如果存在JobAlarm类型的bean，则将它们添加到jobAlarmList中
     * 这对于设置警报功能和处理作业警报至关重要
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化JobAlarm，表明开始处理作业警报的初始化过程
        System.out.println(">>>>>>>>>>> InitializingBean xxl-job 处理作业的警报 start ---> JobAlarm init");

        // 获取应用上下文中所有JobAlarm类型的bean
        Map<String, JobAlarm> serviceBeanMap = applicationContext.getBeansOfType(JobAlarm.class);

        // 如果获取到的JobAlarm类型的bean不为空且数量大于0，则将它们添加到jobAlarmList中
        if (serviceBeanMap != null && serviceBeanMap.size() > 0) {
            jobAlarmList = new ArrayList<JobAlarm>(serviceBeanMap.values());
        }
    }

    /**
     * job alarm
     *
     * @param info
     * @param jobLog
     * @return
     */
    public boolean alarm(XxlJobInfo info, XxlJobLog jobLog) {
        boolean result = false;
        if (jobAlarmList != null && jobAlarmList.size() > 0) {
            result = true;  // success means all-success
            for (JobAlarm alarm : jobAlarmList) {
                boolean resultItem = false;
                try {
                    resultItem = alarm.doAlarm(info, jobLog);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                if (!resultItem) {
                    result = false;
                }
            }
        }

        return result;
    }

}
